package com.twotiger.and.activity.user;

import java.util.HashMap;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import app.twotiger.p2p.R;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.User;
import com.twotiger.and.util.ActivitySwitcher;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.RegexTool;
import com.twotiger.and.util.Tools;
import com.twotiger.and.util.ViewUtils;

public class RegistNextpage extends BaseActivity {

    private static final int REGISTSUCCES = 0;
    private static final int REGISTFAIL = 1;
    private CheckBox psw_isvisable;
    private EditText set_login_psw;
    private Button regist_btn;
    private HashMap<String, String> params;
    private TextView sub_title_center_tv;
    private TextView sub_title_left_tv;
    private TextView tv_backtologin;
    private ImageView iv_finish;
    private View regist_next_root;

    @Override
    protected void processLogic() {
        params = getParm();
        sub_title_center_tv.setText("设置登录密码");
        sub_title_left_tv.setText("取消");
        sub_title_left_tv.setTextColor(getResources().getColor(R.color.gray_1));
        sub_title_left_tv.setVisibility(View.VISIBLE);
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case REGISTSUCCES:
                    Basebean reslut = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (reslut.isOk()) {
                        User user = JSONObject.parseObject(reslut.data, User.class);
                        application.setRegistSuccess(true); //置为true，返回registerpage界面就会消失
                        application.setUser(user);
                        Intent intent = new Intent(getContext(), SetGesturePsdPage.class);
                        intent.putExtra("formregist", true);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);
                    } else {
                        application.setRegistSuccess(false); //置为false，返回registerpage界面不会消失
                        showToast(reslut.codeDesc);
                    }
                    break;
                case REGISTFAIL:
                    application.setRegistSuccess(false); //置为false，返回registerpage界面不会消失
                    showToast("连接失败");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        psw_isvisable.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    set_login_psw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    set_login_psw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        iv_finish.setOnClickListener(this);
        tv_backtologin.setOnClickListener(this);
        regist_btn.setOnClickListener(this);
        sub_title_left_tv.setOnClickListener(this);
        set_login_psw.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim()) || s.toString().length() < 8) {
                    regist_btn.setEnabled(false);
                    ;
                } else {
                    regist_btn.setEnabled(true);
                }
            }
        });
    }

    @Override
    protected void findViewById(View view) {
        psw_isvisable = (CheckBox) view.findViewById(R.id.psw_isvisable);
        set_login_psw = (EditText) view.findViewById(R.id.set_login_psw);
        regist_btn = (Button) view.findViewById(R.id.regist_btn);
        sub_title_left_tv = (TextView) view.findViewById(R.id.sub_title_left_tv);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        tv_backtologin = (TextView) view.findViewById(R.id.tv_backtologin);
        iv_finish = (ImageView)view.findViewById(R.id.iv_finish);
        regist_next_root = view.findViewById(R.id.regist_next_root);
    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.activity_main, null);
        if("forward".equals(getIntent().getStringExtra("isNeedAnim"))){
            ActivitySwitcher.animationInForward(view, getWindowManager());
        }
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.iv_finish:
            finish();
            overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
            break;
        case R.id.tv_backtologin: 
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
//            Intent intent = new Intent(this, LoginPage.class);
//            intent.putExtra("FROM", R.id.tv_backtologin);
//            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);
            final Intent intent1 = new Intent(getApplicationContext(), LoginPage.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            ActivitySwitcher.animationOutBack(regist_next_root, getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() {
                @Override
                public void onAnimationFinished() {
                    startNewActivity(intent1.putExtra("isNeedAnim", "back"), 0, 0, true);
                }
            });
            break;
        case R.id.regist_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String psw = set_login_psw.getText().toString().trim();
            ConstantDataUnit zz_mm = getConstantDataByKey(Constants.zz_mm);
            if(zz_mm != null){
                if (!RegexTool.match(zz_mm.getVal(), psw)) {
                    showToast("密码仅支持8-32位数字,字母和常量符号");
                    return;
                }
            }else {
                if (!RegexTool.match(RegexTool.REG_PASSWORD, psw)) {
                    showToast("密码仅支持8-32位数字,字母和常量符号");
                    return;
                }
            }
            regist(psw);
            break;
        case R.id.sub_title_left_tv:
            onBackPress();
            break;
        default:
            break;
        }
    }

    private void regist(String psw) {
        params.clear();
        params.put("token", getIntent().getStringExtra("registToken"));
        params.put("password", psw);
        params.put("deviceId", Tools.getDeviceId(mContext));
        if (getIntent().getStringExtra("inviteCode") != null) {
            params.put("inviteCode", getIntent().getStringExtra("inviteCode"));
        }
        if(JPushInterface.getRegistrationID(RegistNextpage.this) != null){
            params.put("jpushId", JPushInterface.getRegistrationID(RegistNextpage.this));
        }
        params.put("from", PackageUtils.getAppMetaData(RegistNextpage.this, "UMENG_CHANNEL"));
        postDate(params, Constants.REGIST, handler, REGISTSUCCES, REGISTFAIL, true, false, false);
    }

    @Override
    protected void onBackPress() {
        application.setRegistSuccess(false); //置为false，返回registerpage界面不会消失
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

}
